<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="1400px" append-to-body custom-class="import-dialog"
               @close="close"
    >
      <div class="form-box">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="add-form">
          <div class="section">
            <div class="label">
              <label>房源信息</label>
            </div>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="楼盘" prop="house.estateId">
                  <el-row>
                    <el-col :span="16">
                      <el-input v-model="this.form.house.estateName" placeholder="请选择楼盘"
                                class="form-item__common__input"
                                readonly
                                style="width: 100%"
                      />
                    </el-col>
                    <el-col :span="8">
                      <el-button

                        type="primary"
                        @click="dialogSelectEstateVisible = true"
                      >选择楼盘
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="楼栋、单元" prop="house.houseInfo">
                  <el-cascader
                    v-model="form.house.houseInfo"
                    ref="houseInfo"
                    :props="{
                      value: 'id',
                      label: 'name',
                    }"
                    :options="estateList"
                    @change="handleChange"
                    @visible-change="checkedRegion"
                    class="form-item__common__input"
                  >
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所在楼层" prop="house.floors">
                  <el-select
                    v-model="form.house.floors"
                    placeholder="请选择"
                    @visible-change="checkedHouseInfo"
                    class="form-item__common__input"
                  >
                    <el-option
                      v-for="dict in floorList"
                      :key="dict.value"
                      :label="dict"
                      :value="dict"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="房间号" prop="house.roomNumber">
                  <el-input v-model="form.house.roomNumber" class="form-item__common__input"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="面积" prop="house.houseArea">
                  <el-input v-model="form.house.houseArea" class="form-item__common__input" v-input.float="2">
                    <span slot="append">m<sup>2</sup></span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="朝向" prop="house.houseOrientation">
                  <el-select v-model="form.house.houseOrientation" placeholder="请选择" clearable filterable>
                    <el-option
                      v-for="dict in dict.type.house_orientation"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="户型" required>
                  <el-row>
                    <el-col :span="8">
                      <el-form-item prop="house.roomType">
                        <el-input v-model="form.house.roomType" v-input.int size="mini" maxlength="3">
                          <span slot="append">室</span>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="house.hall">
                        <el-input v-model="form.house.hall" v-input.int size="mini" maxlength="3">
                          <span slot="append">厅</span>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="house.toilet">
                        <el-input v-model="form.house.toilet" v-input.int size="mini" maxlength="3">
                          <span slot="append">卫</span>
                        </el-input>
                      </el-form-item>

                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="可住人数" prop="house.checkInNumber">
                  <el-input v-model="form.house.checkInNumber" v-input.intp class="form-item__common__input">
                    <span slot="append">人</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="房管家" prop="house.houseManagerId">
                  <el-select
                    v-model="form.house.houseManagerId"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="dict in houseManagerList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="业主" prop="house.proprietorUserId">
                  <el-row>
                    <el-col :span="16">
                      <el-input v-model="this.form.house.proprietorName" placeholder="请选择业主"
                                class="form-item__common__input"
                                readonly
                                style="width: 100%"
                      />
                    </el-col>
                    <el-col :span="8">
                      <el-button

                        type="primary"

                        @click="handleSelectProprietor"
                      >选择业主
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="section">
            <div class="label">
              <label>合同信息</label>
            </div>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="合同类型" prop="cooperationType">
                  <el-select v-model="form.cooperationType" placeholder="请选择">
                    <el-option
                      v-for="dict in dict.type.cooperation_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="签署方式" prop="signingMode">
                  <el-select v-model="form.signingMode" placeholder="请选择" @change="signingModeChange">
                    <el-option
                      v-for="dict in dict.type.signing_mode"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同模板" prop="contractTemplateId">
                  <el-select v-model="form.contractTemplateId" placeholder="请选择" clearable @change="contractTemplateChange">
                    <el-option
                      v-for="dict in contractTemplateList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="form.cooperationType == 2">
              <el-col :span="8">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input v-model="form.contractNumber" class="form-item__common__input"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="服务期限" prop="servicePeriodYear">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item prop="servicePeriodYear">
                        <el-input v-model="form.servicePeriodYear" v-input.int>
                          <span slot="append">年</span>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="servicePeriodMonth">
                        <el-input v-model="form.servicePeriodMonth" v-input.int>
                          <span slot="append">月</span>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="筹备期" prop="preparatoryPeriod">
                  <el-input v-model="form.preparatoryPeriod" class="form-item__common__input" v-input.intp>
                    <span slot="append">天</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="收费方式" prop="house.chargeType">
                  <el-select v-model="form.house.chargeType" placeholder="请选择">
                    <el-option
                      v-for="dict in dict.type.charge_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.house.chargeType == 1">
                <el-form-item label="账单服务费" prop="house.serviceCharge">
                  <el-input v-model="form.house.serviceCharge" class="form-item__common__input"
                            @change="(e)=>this.form.house.serviceCharge = Number(e)" v-input.float="1"
                  >
                    <span slot="append">%</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.house.chargeType == 2">
                <el-form-item label="费用金额" prop="house.feeAmount">
                  <el-input v-model="form.house.feeAmount" class="form-item__common__input"
                            @change="(e)=>this.form.house.feeAmount = Number(e)" v-input.float="2"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.house.chargeType == 2">
                <el-form-item label="最晚付款日期" prop="house.latestPaymentDate">
                  <el-date-picker
                    v-model="form.house.latestPaymentDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd 23:59:59"
                    :picker-options="latestPaymentDatePickerOption"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最晚签约日期" prop="latestSigningDate">
                  <el-date-picker
                    v-model="form.latestSigningDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="form.cooperationType == 1">
              <el-col :span="8">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input v-model="form.contractNumber" class="form-item__common__input"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="租赁期限" prop="leaseStartDate">
                  <el-date-picker
                    v-model="form.leaseDate"
                    type="daterange"
                    range-separator="————"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="leaseDateChange"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="租金" prop="monthRent">
                  <el-input v-model="form.monthRent" class="form-item__common__input"
                            @change="(e)=>this.form.monthRent = Number(e)" v-input.float="2"
                  >
                    <span slot="append">元/月</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="押金" prop="cashPledge">
                  <el-input v-model="form.cashPledge" class="form-item__common__input"
                            @change="(e)=>this.form.cashPledge = Number(e)" v-input.float="2"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最晚签约日期" prop="latestSigningDate">
                  <el-date-picker
                    v-model="form.latestSigningDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--  选择楼盘  -->
    <SelectEstate v-model="dialogSelectEstateVisible" :selected="selectedEstateId" :is-multiple="false"
                  @success="selectEstateCb"
    />
    <!--  选择业主  -->
    <SelectProprietor :cooperationType="form.cooperationType" v-model="dialogSelectProprietorVisible"
                      :selected="selectedList" :is-multiple="false" @success="selectProprietorCb"
    />
  </div>
</template>

<script>

function filterUnit(id, arr) {
  for (const item of arr) {
    console.log('item', item)
    if (item.id == id) return item
    if (item.children && item.children.length > 0) {
      const _item = filterUnit(id, item.children)
      if (_item) return _item
    }
  }
}

import { addProprietorContract } from '@/api/contract/proprietor'
import { listBuildingArray } from '@/api/house/estate'
import { houseManagerList, listContractTemplate, pageElectronicVisa } from '@/api/contract/proprietor'
import SelectEstate from '@/views/long-short-rent/contract/proprietor/components/select-estate.vue'
import SelectProprietor from '@/views/long-short-rent/contract/proprietor/components/select-proprietor.vue'
import rules from '@/views/long-short-rent/contract/proprietor/components/rules'
import { debounce } from '@/utils'

export default {
  name: 'add',
  dicts: ['house_orientation', 'proprietor_contract_status', 'cooperation_type', 'signing_mode', 'charge_type'],
  components: {
    SelectEstate,
    SelectProprietor
  },
  props: {
    title: {
      default: '新增业主合同'
    },
    value: {
      default: false
    },
    contractId: {
      default: undefined
    },
    isDetail: {
      default: false
    },
    success: {
      type: Function,
      default: () => {
      }
    }
  },
  data() {
    return {
      visible: false,
      currentTab: '0',
      dialogSelectHouseVisible: false,
      //选择楼盘弹窗
      dialogSelectEstateVisible: false,
      //选择业主弹窗
      dialogSelectProprietorVisible: false,
      //合同列表
      contractList: [],
      //已选择列表
      selectedList: [],
      //已选择楼盘Id
      selectedEstateId: '',
      estateNames: '',
      // 楼层列表
      floorList: [],
      //楼盘列表
      estateList: [],
      //房管家列表
      houseManagerList: [],
      form: {
        house: {}
      },
      latestPaymentDatePickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      // 合同模板列表
      contractTemplateList: [],
      templateType: ''
    }
  },
  computed: {
    rules() {
      return rules.rulesFn(this)
    }
  },
  watch: {
    value(newVal) {
      if (newVal) {
        this.init()
      }
      this.visible = newVal // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit('input', val) // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    },
    'form.cooperationType': {
      handler(val) {
        let templateType = ''
        if (val == 1) {
          templateType = '3'
        } else if (val == 2) {
          templateType = '4'
        }
        this.templateType = templateType
        this.signingModeChange()
      },
      deep: true,
      immediate: true
    },
  },
  mounted() {
    this.visible = this.value
  },
  methods: {
    init() {
      //重置
      this.reset()
      //获取房管家列表
      this.getHouseManagerList()
    },
    //重置表单
    reset() {
      this.form = {
        cashPledge: undefined, //押金
        monthRent: undefined, //月租金
        contractTemplateId: undefined,//合同模版id
        contractTemplateName: undefined,//合同模版名称
        cooperationType: '2',//合作方式:1.房屋委托;2.代理服务(字典字段:cooperation_type)
        signingMode: '1',//签署方式:1.电子合同;2.纸质合同(字典字段:signing_mode)
        contractNumber: '',//合同编号
        servicePeriodYear: undefined,//服务期限年份
        servicePeriodMonth: undefined,//服务期限月份
        preparatoryPeriod: undefined,//筹备期
        latestSigningDate: '',//最晚签约日期
        leaseStartDate: '',//租赁开始时间
        leaseEndDate: '',//租赁结束时间
        leaseDate: '',// 租赁时间数组
        house: {
          estateId: '',//楼盘id
          estateName: '',//楼盘名
          buildingId: '',//楼栋id
          buildingName: '',//楼栋名
          unitId: '',//单元id
          unitName: '',//单元名
          floors: undefined, //楼层
          roomNumber: '',//房间号
          houseArea: undefined, //面积
          houseOrientation: '', //朝向
          roomType: '', //室
          hall: '', //厅
          toilet: '', //卫
          checkInNumber: undefined, //可住人数
          houseManagerId: undefined, //房管员id
          proprietorUserId: null, //业主id
          proprietorName: null,//业主名称
          // 'remark': null,
          // 'tenantId': '1', //机构id
          // 'houseNature': '4',
          // 'houseType': '1',
          // 'houseState': '2',
          // 'houseLeaseState': null,
          // 'houseMaintainState': null,
          // 'waterMeterNumber': null,
          // 'electricMeterNumber': null,
          // 'gasMeterNumber': null,
          // 'houseQrCode': null,
          // 'provinceId': '65',
          // 'provinceName': '新疆维吾尔自治区',
          // 'cityId': '6501',
          // 'cityName': '乌鲁木齐市',
          // 'districtId': '650103',
          // 'districtName': '沙依巴克区',
          // 'streetId': '650103001',
          // 'streetName': '长江路街道',
          // 'communityId': '650103001001', //所属社区id
          // 'communityName': '经一路社区居委会',
          // 'premisesAddress': '天池怨1栋1单元902号', //小区地址
          // 'fullAddress': '新疆维吾尔自治区乌鲁木齐市沙依巴克区长江路街道天池怨1栋1单元902号',
          // 'delFlag': '0',
          chargeType: '1', //收费方式:1.账单服务费;2.一次性服务费(字典字段:charge_type)
          serviceCharge: undefined, //账单服务费
          feeAmount: undefined, //费用金额（2.一次性服务费时显示）
          latestPaymentDate: '' //最晚付款日期(2.一次性服务费时显示)
          // 'rentalLicenseNumber': null, //房屋租赁许可证号
          // 'houseCheckCode': null, //房源核验码
        } //房屋信息
      }

      this.resetForm('form')
      this.selectedEstateId = ''
    },
    //获取房管家列表
    getHouseManagerList() {
      let params = {
        roleKey: 'houseKeeper'
      }
      houseManagerList(params).then(response => {
        this.houseManagerList = response.data.map(item => {
          return {
            label: item.userName,
            value: item.userId
          }
        })
      })
    },
    //选择楼盘回调
    selectEstateCb(data) {
      if (data) {
        this.selectedEstateId = data.estateId
        this.form.house.estateName = data.estateName
        this.form.house.estateId = data.estateId
        //重置楼栋、单元内容
        this.form.house.buildingId = ''
        this.form.house.buildingName = ''
        this.form.house.unitId = ''
        this.form.house.unitName = ''

        // 获取楼栋、单元
        this.getlistBuilding()
      }
    },
    selectProprietorCb(data) {
      this.form.house.proprietorName = data.proprietorName
      this.form.house.proprietorUserId = data.conUserId
    },
    /** 查询楼栋、单元集合 */
    getlistBuilding() {
      this.loading = true
      listBuildingArray({ estateId: this.form.house.estateId }).then((response) => {
        //重置楼层内容
        this.form.house.floors = ''

        this.estateList = response
        if (this.form.house.unitId) {
          let data = filterUnit(this.form.house.unitId, this.estateList)
          let floorList = []
          let number = data.number
          let i = 1
          while (i <= number) {
            floorList.push(i)
            i++
          }
          this.floorList = floorList
        }
      })
    },
    handleChange(e) {
      console.log('e', e)
      const checkedNodes = this.$refs['houseInfo'].getCheckedNodes()
      console.log('checkedNodes', checkedNodes)
      const ids = checkedNodes[0].path
      const labels = checkedNodes[0].pathLabels

      //重置楼层内容
      this.form.house.floors = ''

      let floorList = []
      let number = checkedNodes[0].data.number
      let i = 1
      while (i <= number) {
        floorList.push(i)
        i++
      }
      this.floorList = floorList

      this.form.house.buildingId = ids[0]
      this.form.house.buildingName = labels[0]
      this.form.house.unitId = ids[1]
      this.form.house.unitName = labels[1]
    },
    checkedHouseInfo(e) {
      if (!this.form.house.houseInfo && e) {
        this.$modal.closeAll()
        this.$modal.msgError('请先选择楼栋、单元')
      }
    },
    //检测是否选择区域
    checkedRegion(e) {
      if (this.form.estateId == '' && e) {
        this.$modal.closeAll()
        this.$modal.msgError('请先选择楼盘')
      }
    },
    //租赁周期变化回调
    leaseDateChange(e) {
      if (e) {
        this.form.leaseStartDate = e[0]
        this.form.leaseEndDate = e[1]
      } else {
        this.form.leaseStartDate = ''
        this.form.leaseEndDate = ''
      }

    },
    //选择业主
    handleSelectProprietor() {
      if (!this.form.cooperationType) {
        this.$message.error('请选择合同类型')
        return
      }
      this.dialogSelectProprietorVisible = true
    },
    //签署方式改变
    signingModeChange(val) {
      if(val){
        this.form.contractTemplateId = ''
        this.form.contractTemplateName = ''
      }
      if (this.form.signingMode === '1') {
        let params = {
          // templateType: this.templateType
          // templateName: '甲方企业',
          templateName:'房屋代理出租合同'
        }
        pageElectronicVisa(params).then(response => {
          this.contractTemplateList = response.data.signTemplates.map(item => {
            return {
              label: item.signTemplateName,
              value: item.signTemplateId
            }
          })
        })
      }
      if (this.form.signingMode === '2') {
        let params = {
          contractTemplateName: '',
          templateState: '0',
          templateType: this.templateType
        }
        listContractTemplate(params).then(response => {
          this.contractTemplateList = response.data.map(item => {
            return {
              label: item.contractTemplateName,
              value: item.contractTemplateId
            }
          })
        })
      }
    },
    //选择合同模板改变
    contractTemplateChange(val) {
      this.contractTemplateList.find(item => {
        if (item.value == val) {
          this.form.contractTemplateName = item.label
          this.form.contractTemplateId = val
        }
      })
    },
    //提交表单
    submitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addProprietorContract(this.form).then(res => {
            this.$message.success(res.msg)
            this.$emit('success')
            this.visible = false
          })
        }
      })
    }, 300),
    //关闭
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-footer {
    text-align: center;
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.form-box {
  .add-form {
    margin-top: 30px;

    .section {
      .label {
        display: flex;
        margin-bottom: 20px;
        font-size: 16px;
        align-items: center;
        color: #303133;

        label {
          display: block;
          width: 80px;

          &.dot::before {
            content: "*";
            color: #ff4949;
            margin-right: 4px;
          }
        }

      }
    }

    .form-item__common__input {
      width: 240px;
    }
  }
}
</style>

